#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：back 
@File    ：aliyun_oss.py
@IDE     ：PyCharm 
@Author  ：七分是你
@Date    ：2024/7/2 下午1:35 
@explain : 
"""
import oss2

from app.config import globalAppSettings


class AliyunOSS:

    def __init__(self, access_key_id=globalAppSettings.access_key_id,
                 access_key_secret=globalAppSettings.access_key_secret, endpoint=globalAppSettings.endpoint,
                 bucket_name=globalAppSettings.bucket_name):
        self.auth = oss2.Auth(access_key_id, access_key_secret)
        self.bucket = oss2.Bucket(self.auth, endpoint, bucket_name)

    def upload_file(self, key, data):
        try:
            self.bucket.put_object(key, data)
            return True
        except oss2.exceptions.OssError as e:
            print(f"文件上传失败：{e.status} - {e.details}")
            return False

    def download_file(self, oss_file_name, local_file_path):
        try:
            self.bucket.get_object_to_file(oss_file_name, local_file_path)
            print(f"文件下载成功：{oss_file_name}")
            return True
        except oss2.exceptions.OssError as e:
            print(f"文件下载失败：{e.status} - {e.details}")
            return False

    def delete_file(self, oss_file_name):
        try:
            self.bucket.delete_object(oss_file_name)
            print(f"文件删除成功：{oss_file_name}")
            return True
        except oss2.exceptions.OssError as e:
            print(f"文件删除失败：{e.status} - {e.details}")
            return False

    def list_files(self, prefix=''):
        try:
            for obj in self.bucket.list_objects(prefix=prefix):
                print(obj.key)
            return True
        except oss2.exceptions.OssError as e:
            print(f"文件列表获取失败：{e.status} - {e.details}")
            return False
